import { User } from '../entity/user.entity';
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import * as bcrypt from 'bcrypt';
import { JwtService } from '@nestjs/jwt';
import * as crypto from 'crypto-js';
import { WEB_SALE_VALUE,JWT_TOKEN_EXPIRES_IN } from '../config/constant';
@Injectable()
export class AuthService {
    public constructor(
        @InjectRepository(User) private user: Repository<User>,
        private readonly jwtService: JwtService,
    ) {}

    // JWT验证 - Step 2: 校验用户信息
    public async validateUser(username: string, pwd: string): Promise<any> {
        console.log('validateUser:',username)
        console.log('validateUser:',pwd)
        const user = await this.user.findOne({
            select: ['username', 'password','id'],
            where: {
                username,
            },
        });

        console.log('校验搜索内容：',user)
        if (user && bcrypt.compare(pwd, user.password)) {
            return new Promise((resolve, reject) => {
                resolve(user);
            });
        } else {
             return user && bcrypt.compare(pwd, user.password);
        }

    }

    // JWT验证 - Step 3: 处理 jwt 签证
    public certificate(user: any): string {

        // 这里对jwt的内容采用了 crypto 中的aes的对称加密方法
        const payload = {
            info: crypto.AES.encrypt(
                JSON.stringify({ username: user.username, password: user.password }),
                'salt',
            ).toString(),
            // userId:user.userId,
            sub: user.id,
            expiresIn:JWT_TOKEN_EXPIRES_IN
        };
        console.log('sign:',payload)
        return this.jwtService.sign(payload);
    }


}